package filter;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "daoFilter",urlPatterns = "/dao/*")
public class daoFilter implements Filter {
    private EntityManagerFactory emf;

    @Override
    public void init(FilterConfig filterConfig) {
         emf = Persistence.createEntityManagerFactory("myJPA");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        System.out.println("[" + ((HttpServletRequest)request).getRequestURI() + "],EntityManagerFilter拦截成功");

        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        tx.begin();

        request.setAttribute("_entity.Manager", em);

        try {
            chain.doFilter(request, response);

            tx.commit();
        } catch (RuntimeException | ServletException th) {

            tx.rollback();

            throw th;

        } finally {
            em.close();
        }
    }

    @Override
    public void destroy() {
        emf.close();
    }
}
